# handle_post_friendfeed.py - Handle queue requests to post to Friendfeed.
# Copyright 2010 Rob Myers <rob@robmyers.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import friendfeed # v1 api!!!

import logging
import post_data
import traceback
import urllib
import urllib2
import yaml

import wsgiref.handlers
from google.appengine.runtime import DeadlineExceededError
from google.appengine.ext import webapp

class FriendfeedWorker(webapp.RequestHandler):
    def message_body(self, data):
        message = ''
        if data.title:
            message = data.title
        elif data.decription:
            message = data.description
        return message

    def post(self):
        dgr_yaml_path = self.request.get('dgr-yaml-path')
        post_json = self.request.get('post-data')
        if(dgr_yaml_path and post_data):
            try:
                logging.info('Posting to Friendfeed')
                data = post_data.PostData().from_json(post_json)
                config = yaml.safe_load(file(dgr_yaml_path, 'r'))
                session = friendfeed.FriendFeed(config['friendfeed_nickname'],
                                                config['friendfeed_remote_key'])
                
                # This is a hack, but other posting handlers need the url
                image_urls = []
                if data.source_url.find('youtube') == -1:
                    image_urls = [data.image_url]

                result = session.publish_link(self.message_body(data),
                                              data.source_url,
                                              image_urls=image_urls)
                logging.info(result)
                logging.info('Posted to Friendfeed')
            except Exception, e:
                logging.error(type(e))
                logging.error(e)
                logging.error(traceback.format_exc())

def main():
    wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
                ('/post-friendfeed', FriendfeedWorker)], debug=True))
    
if __name__ == '__main__':
    logging.getLogger().setLevel(logging.DEBUG)
    main()
